package web.test.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import web.test.exception.BizException;

@Component
public class ErrorFilter extends ZuulFilter {

    protected static ThreadLocal<ExceptionInfo> hasBizException = new ThreadLocal();

    protected static class ExceptionInfo {
        private boolean error;
        private BizException bizException;

        public ExceptionInfo(boolean error, BizException bizException) {
            this.error = error;
            this.bizException = bizException;
        }

        public boolean isError() {
            return error;
        }

        public void setError(boolean error) {
            this.error = error;
        }

        public BizException getBizException() {
            return bizException;
        }

        public void setBizException(BizException bizException) {
            this.bizException = bizException;
        }
    }

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        Throwable throwable = requestContext.getThrowable();
        if(throwable != null && throwable instanceof BizException){
            hasBizException.remove();
            hasBizException.set(new ExceptionInfo(true, (BizException) throwable));

        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        return null;
    }
}
